/**
 * @Description:
 * @Author: CHEHSHUANG
 * @Date: 2019/3/14
 */
import React, {Component, Fragment} from 'react';
import {accountDelete, accountSave, listAllUserAccountByUserId, updatePassword} from "../service";
import {connect} from "react-redux";
import {hide, show} from "../../../configs/SharedReducer";
import SimpleTable from "../../../commons/components/SimpleTable";
import StandardDropdown from "../../../commons/components/StandardDropdown";
import ToolBar from "../../../commons/components/toolbar/ToolBar";
import {searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import AddOrEditAccountModal from "./AddOrEditAccountModal";
import {message} from "antd";
import {confirm} from "../../../commons/components/StandardModal";
import PasswordEditModal from "./PasswordEditModal";

class AccountInfo extends Component {
  state = {
    dataSource: [],
    searchData: [],
    addVisible: false,
    passwordVisible: false,
    flag: ""
  }

  componentDidMount() {
    this.getDataSource();
  }

  getFormRef = (ref) => {
    this.formRef = ref;
  }
  getPasswordFormRef = (ref) => {
    this.passwordRef = ref;
  }
  getDataSource = () => {
    const {userId} = this.props;
    listAllUserAccountByUserId({userId})
      .then(res => {
        this.setState({dataSource: res});
      })
      .finally(() => {

      })
  }
  handleAdd = () => {
    this.setState({flag: "add"});
    this.setModalVisible(true);
  }
  handlePassword = (record) => {
    this.setState({editData: record});
    this.setPasswordModalVisible(true);
  }
  handleEdit = (record) => {
    this.setState({editData: record, flag: "edit"});
    this.setModalVisible(true);
  }
  setModalVisible = (visible) => {
    this.setState({addVisible: visible})
  }
  setPasswordModalVisible = (visible) => {
    this.setState({passwordVisible: visible})
  }
  handleDelete = (record) => {
    if (!record) return;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk: () => {
        this.props.show();
        accountDelete(record.id).then(res => {
          if(res.status === "SUCCESS"){
            message.success(res.message || "删除成功");
            this.getDataSource();
          }else{
            message.error(res.message || "删除失败!");
          }
        }).catch(e => {
        }).finally(() => {
          this.props.hide()
        })
      }
    });
  }
  //保存账号
  handleSave = () => {
    const saveData = this.formRef.getFormValue();
    if (saveData) {
      this.setState({confirmLoading: true});
      accountSave(saveData).then(res => {
        if(res.status === "SUCCESS"){
          message.success(res.message || "保存成功");
          this.setModalVisible(false);
          this.getDataSource();
        }else{
          message.error(res.message || "保存失败!");
        }
      }).catch(e => {
      }).finally(() => {
        this.setState({confirmLoading: false});
      })
    }
  }
  //保存密码
  handleSavePassword = () => {
    const saveData = this.passwordRef.getFormValue();
    if (saveData) {
      this.setState({confirmLoading: true});
      updatePassword(saveData).then(res => {
        if(res.status==="SUCCESS"){
          message.success(res.message || "修改成功，下次登陆时请使用新密码!");
          this.setPasswordModalVisible(false);
          this.getDataSource();
        }else{
          message.error(res.message || "修改失败!");
        }
      }).catch(e => {
      }).finally(() => {
        this.setState({confirmLoading: false});
      })
    }
  }
  getColumns = () => {
    return [
      {
        title: "操作",
        width: 150,
        dataIndex: "operator",
        render: (text, record, index) => {
          const buttons = [
            <a className={'row-operator-item'} key={"edit"} onClick={() => this.handleEdit(record)}>编辑</a>,
            <a className={'row-operator-item'} key={"password"} onClick={() => this.handlePassword(record)}>修改密码</a>,
            <a className={'row-operator-item'} key={"del"} onClick={() => this.handleDelete(record)}>删除</a>
          ];
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <StandardDropdown
                operator={buttons}
              />
            </div>
          )
        }
      },
      {
        title: "昵称",
        width: 200,
        dataIndex: "nickName"
      },
      {
        title: "账号",
        width: 200,
        dataIndex: "account"
      }
    ];
  }
  handleQuickSearch = (searchValue) => {
    this.setState({searchValue})
    searchListByKeyWithTag(this.state.dataSource, {keyword: searchValue}, ['nickName', 'account']);
  }
  searchBtnCfg = () => {
    return {
      quickSearchCfg: {
        style: {width: 250},
        placeholder: "输入昵称或账号查询",
        allowClear: true,
        onSearch: (v) => {
          this.handleQuickSearch(v)
        }
      }
    }
  }
  btnsCfg = () => {
    return [
      {
        title: "新增",
        propsCfg: {
          type: "primary",
          onClick: () => {
            this.handleAdd()
          }
        }
      }];
  }

  render() {
    const {dataSource, searchValue, addVisible, editData, flag, passwordVisible, confirmLoading} = this.state;
    return (
      <Fragment>
        <ToolBar
          btnsCfg={this.btnsCfg()}
          searchBtnCfg={this.searchBtnCfg()}
        />
        <SimpleTable
          data={searchValue ? dataSource.filter(item => item.tag===true) : dataSource}
          columns={this.getColumns()}
        />
        {
          addVisible && <AddOrEditAccountModal
            flag={flag}
            confirmLoading={confirmLoading}
            visible={addVisible}
            editData={editData}
            onRef={this.getFormRef}
            onOk={this.handleSave}
            onCancel={() => this.setModalVisible(false)}
          />
        }
        {
          passwordVisible && <PasswordEditModal
            confirmLoading={confirmLoading}
            visible={passwordVisible}
            editData={editData}
            onRef={this.getPasswordFormRef}
            onOk={this.handleSavePassword}
            onCancel={() => this.setPasswordModalVisible(false)}
          />
        }
      </Fragment>
    );
  }
}

export default connect(null, {show, hide})(AccountInfo);
